package com.mbc.rmt.manager;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;

import com.mbc.common.CommonSingleton;
import com.mbc.common.dao.CommonDAOFactory;
import com.mbc.common.dao.CurrencyRateDetailDAO;
import com.mbc.common.dao.LogDAO;
import com.mbc.common.entities.CurrencyRateDetail;
import com.mbc.common.entities.Log;
import com.mbc.common.exception.DataDuplicationException;
import com.mbc.common.manager.AbstractMgr;
import com.mbc.common.utils.KeyGenerator;
import com.mbc.rmt.dao.AgentBalanceDAO;
import com.mbc.rmt.dao.OpeningAgentDAO;
import com.mbc.rmt.dao.RemittanceDAOFactory;
import com.mbc.rmt.data.OpeningAgentDataList;
import com.mbc.rmt.entities.AgentBalance;
import com.mbc.rmt.entities.OpeningAgent;
import com.mbc.rmt.entities.OpeningAgentRpt;

public class OpeningAgentMgr extends AbstractMgr {

	private OpeningAgentDAO openingagentDAO;
	private AgentBalanceDAO agentbalanceDAO;
	private CurrencyRateDetailDAO currencyrateDetailDAO;
	private LogDAO logDAO;

	public OpeningAgentMgr() {
	}

	public OpeningAgentMgr(String sessionId) {
		this.sessionId = sessionId;
	}

	public void create(OpeningAgent entity) throws Exception {
		openConnection();
		try {
			beginTransaction();
			openingagentDAO = RemittanceDAOFactory.getOpeningAgentDAO(dbManager
					.getConnection());
			agentbalanceDAO = RemittanceDAOFactory.getAgentBalanceDAO(dbManager
					.getConnection());
			currencyrateDetailDAO = CommonDAOFactory.getCurrencyRateDetailDAO(dbManager.getConnection());
			logDAO = CommonDAOFactory.getLogDAO(getConnection());
			
			OpeningAgent l_info = new OpeningAgent();
			l_info = openingagentDAO.find(entity.getInvoice_Id());
			if (l_info != null) {
				throw new Exception("Invoice ID already exists!");
			} else {
//				CurrencyRate l_currencyrate = null;
				CurrencyRateDetail l_currencyrateDetail = new CurrencyRateDetail();
//				if (entity.getCurrency_rate_Id() == 0){
//					 l_currencyrate = currencyrateDAO.find(entity.getCurrency_Id(),entity.getCurrency_Id(),entity.getBranchId());
//					  if(l_currencyrate ==null){
//					   l_currencyrate = new CurrencyRate();
//					   l_currencyrate.setCurrencyRateId(KeyGenerator.generateKey(getConnection()));
//					   l_currencyrate.setCurrencyRateCode(entity.getCurrency_rate_Code());
//					   l_currencyrate.setDescription("");
//					   l_currencyrate.setSourceCurrencyId(entity.getCurrency_Id());
//					   l_currencyrate.setConvertCurrencyId(entity.getCurrency_Id());
//					   l_currencyrate.setRoper("D");
//					   l_currencyrate.setBranchId(entity.getBranchId());
//					   currencyrateDAO.create(l_currencyrate);
//					  }
//				}
				if(entity.getRate() !=1){
					l_currencyrateDetail = currencyrateDetailDAO.findLatest(entity.getCurrency_rate_Id());
					if ( l_currencyrateDetail.getRate() != entity.getRate()){
				   
					   l_currencyrateDetail.setCurrencyRateDetailId(KeyGenerator.generateKey(getConnection()));
					   l_currencyrateDetail.setCurrencyRateId(entity.getCurrency_rate_Id());
					   l_currencyrateDetail.setRate(entity.getRate());
					   l_currencyrateDetail.seteDateTime(entity.getOpeningagentDate());
					   currencyrateDetailDAO.create(l_currencyrateDetail);
					   
					   Log l_logentity = new Log();
					   l_logentity.setTablename("CurrencyRateDetail");
					   l_logentity.setLogkey(KeyGenerator.generateKey(getConnection()));
					   l_logentity.setKey(l_currencyrateDetail.getCurrencyRateDetailId());
					   l_logentity.setLogstatus(Log.__SAVE_DATA);
					   logDAO.getData(l_logentity);
					   
					}
				}
				entity.setInvoice_Id(KeyGenerator.generateKey(getConnection()));
		        openingagentDAO.create(entity);
		        
		        Log l_logentity = new Log();
		        l_logentity.setTablename("OpeningAgent");
		        l_logentity.setLogkey(KeyGenerator.generateKey(getConnection()));
		        l_logentity.setKey(entity.getInvoice_Id());
		        l_logentity.setUserid(entity.getUserId());
		        l_logentity.setLogstatus(Log.__SAVE_DATA);
		        logDAO.getData(l_logentity);
		        
				if (entity.getL_AgentBalance() != null) {
						AgentBalance l_AgentBalance = new AgentBalance();
						l_AgentBalance.setAgent_id(entity.getL_AgentBalance().getAgent_id());
						l_AgentBalance.setCurrencyid(entity.getL_AgentBalance().getCurrencyid());
						l_AgentBalance = agentbalanceDAO.getInfo(l_AgentBalance);
	
				if (l_AgentBalance == null) {
						entity.getL_AgentBalance().setAgentbalance_id(KeyGenerator.generateKey(getConnection()));
						agentbalanceDAO.create(entity.getL_AgentBalance());
					} else {
						entity.getL_AgentBalance().setAgentbalance_id(l_AgentBalance.getAgentbalance_id());
						entity.getL_AgentBalance().setOpeningbalance(l_AgentBalance.getOpeningbalance()- entity.getC_amt()+ entity.getL_AgentBalance().getOpeningbalance());
						entity.getL_AgentBalance().setCurrentbalance(l_AgentBalance.getCurrentbalance()- entity.getC_amt()+ entity.getL_AgentBalance().getCurrentbalance());
						agentbalanceDAO.update(entity.getL_AgentBalance());
						}
					}
				}
			commintTransaction();
		} catch (SQLException e) {
			if (DataDuplicationException.UNIQUE_KEY_ERROR_CODE == e
					.getErrorCode())
				throw new DataDuplicationException(e.getMessage());
			rollbackTransaction();
			throw e;
		} finally {
			closeConnection();
		}
	}

	public void update(OpeningAgent entity) throws Exception {
		openConnection();
		try {
			beginTransaction();
			openingagentDAO = RemittanceDAOFactory.getOpeningAgentDAO(dbManager.getConnection());
			logDAO = CommonDAOFactory.getLogDAO(getConnection());
			openingagentDAO.update(entity);
			
			 Log l_logentity = new Log();
			 l_logentity.setTablename("OpeningAgent");
		        l_logentity.setLogkey(KeyGenerator.generateKey(getConnection()));
		        l_logentity.setKey(entity.getInvoice_Id());
		        l_logentity.setUserid(entity.getUserId());
		        l_logentity.setLogstatus(Log.__UPDATE_DATA);
		        logDAO.getData(l_logentity);
		        
			currencyrateDetailDAO = CommonDAOFactory.getCurrencyRateDetailDAO(dbManager.getConnection());
			CurrencyRateDetail l_currencyrateDetail = new CurrencyRateDetail();
			if(entity.getRate() !=1){
				l_currencyrateDetail = currencyrateDetailDAO.findLatest(entity.getCurrency_rate_Id());
				if (l_currencyrateDetail.getRate() != entity.getRate())
				{
					l_currencyrateDetail.setCurrencyRateDetailId(KeyGenerator.generateKey(getConnection()));
					l_currencyrateDetail.setCurrencyRateId(entity.getCurrency_rate_Id());
					l_currencyrateDetail.setRate(entity.getRate());
					l_currencyrateDetail.seteDateTime(entity.getOpeningagentDate());
					currencyrateDetailDAO.create(l_currencyrateDetail);
					
				   l_logentity.setTablename("CurrencyRateDetail");
				   l_logentity.setLogkey(KeyGenerator.generateKey(getConnection()));
				   l_logentity.setKey(l_currencyrateDetail.getCurrencyRateDetailId());
				   l_logentity.setLogstatus(Log.__UPDATE_DATA);
				   logDAO.getData(l_logentity);
				}
			}
			if (entity.getL_AgentBalance() != null) {
			  agentbalanceDAO = RemittanceDAOFactory.getAgentBalanceDAO(dbManager.getConnection());
			  
			  if (entity.getDiff_AgentStatus().equals("true")) {
				  
				AgentBalance l_UAgentBalance = new AgentBalance();
				l_UAgentBalance.setAgent_id(entity.getC_agentId());
				l_UAgentBalance.setCurrencyid(entity.getC_currencyId());
				l_UAgentBalance = agentbalanceDAO.getInfo(l_UAgentBalance);
				if (l_UAgentBalance != null) {
					l_UAgentBalance.setAgentbalance_id(l_UAgentBalance.getAgentbalance_id());
					l_UAgentBalance.setOpeningbalance(l_UAgentBalance.getOpeningbalance() - entity.getC_amt());
					l_UAgentBalance.setCurrentbalance(l_UAgentBalance.getCurrentbalance() - entity.getC_amt());
					agentbalanceDAO.update(l_UAgentBalance);
				}
				
				AgentBalance l_infoAgentBalance = new AgentBalance();
				l_infoAgentBalance.setAgent_id(entity
						.getL_AgentBalance().getAgent_id());
				l_infoAgentBalance.setCurrencyid(entity
						.getL_AgentBalance().getCurrencyid());
				l_infoAgentBalance = agentbalanceDAO.getInfo(l_infoAgentBalance);
				if (l_infoAgentBalance == null) {
					entity.getL_AgentBalance().setAgentbalance_id(KeyGenerator.generateKey(getConnection()));
					agentbalanceDAO.create(entity.getL_AgentBalance());
				} else {
					entity.getL_AgentBalance().setAgentbalance_id(l_infoAgentBalance.getAgentbalance_id());
					entity.getL_AgentBalance().setOpeningbalance(l_infoAgentBalance.getOpeningbalance()+ entity.getL_AgentBalance().getOpeningbalance());
					entity.getL_AgentBalance().setCurrentbalance(l_infoAgentBalance.getCurrentbalance()+ entity.getL_AgentBalance().getCurrentbalance());
					agentbalanceDAO.update(entity.getL_AgentBalance());
				}
			} else { //false
				AgentBalance l_infoAgentBalance = new AgentBalance();
				l_infoAgentBalance.setAgent_id(entity.getC_agentId());
				l_infoAgentBalance.setCurrencyid(entity.getC_currencyId());
				l_infoAgentBalance = agentbalanceDAO.getInfo(l_infoAgentBalance);

				if (l_infoAgentBalance != null) {
					entity.getL_AgentBalance().setAgentbalance_id(l_infoAgentBalance.getAgentbalance_id());
					entity.getL_AgentBalance().setCurrentbalance(l_infoAgentBalance.getCurrentbalance()- entity.getC_amt()+ entity.getL_AgentBalance().getCurrentbalance());
					entity.getL_AgentBalance().setOpeningbalance(l_infoAgentBalance.getOpeningbalance()- entity.getC_amt()+ entity.getL_AgentBalance().getOpeningbalance());
					agentbalanceDAO.update(entity.getL_AgentBalance());
				}
			}

		}
			
		commintTransaction();
		} catch (Exception e) {
			rollbackTransaction();
			throw e;
		} finally {
			closeConnection();
		}
	}

	public void delete(long key,long userid , AgentBalance agentBalance) throws Exception {
		openConnection();
		try {
			openingagentDAO = RemittanceDAOFactory.getOpeningAgentDAO(dbManager
					.getConnection());
			agentbalanceDAO = RemittanceDAOFactory.getAgentBalanceDAO(dbManager
					.getConnection());
			logDAO = CommonDAOFactory.getLogDAO(getConnection());
			
			Log l_logentity = new Log();
			l_logentity.setTablename("OpeningAgent");
			l_logentity.setLogkey(KeyGenerator.generateKey(getConnection()));
			l_logentity.setKey(key);
			l_logentity.setUserid(userid);
			l_logentity.setLogstatus(Log.__DELETE_DATA);
			logDAO.getData(l_logentity);
			
			openingagentDAO.delete(key);
			AgentBalance l_AgentBalance=new AgentBalance();
			l_AgentBalance.setAgent_id(agentBalance.getAgent_id());
			l_AgentBalance.setCurrencyid(agentBalance.getCurrencyid());
			l_AgentBalance=agentbalanceDAO.getInfo(l_AgentBalance);
			if(l_AgentBalance != null)
			{
				l_AgentBalance.setOpeningbalance(l_AgentBalance.getOpeningbalance()-agentBalance.getOpeningbalance());
				l_AgentBalance.setCurrentbalance(l_AgentBalance.getCurrentbalance()-agentBalance.getCurrentbalance());
				agentbalanceDAO.update(l_AgentBalance);
			}
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}
	}

	public OpeningAgent find(long key) throws Exception {
		openConnection();
		try {
			openingagentDAO = RemittanceDAOFactory.getOpeningAgentDAO(dbManager
					.getConnection());
			return openingagentDAO.find(key);
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}
	}

	public OpeningAgent getOpeningAgent(long key) throws Exception {
		openConnection();
		try {
			openingagentDAO = RemittanceDAOFactory.getOpeningAgentDAO(dbManager
					.getConnection());
			return openingagentDAO.getOpeningAgent(key);
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}
	}

	public OpeningAgent findByCode(String code,long branchId) throws Exception {
		openConnection();
		try {
			openingagentDAO = RemittanceDAOFactory.getOpeningAgentDAO(dbManager
					.getConnection());
			return openingagentDAO.findByCode(code,branchId);
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}
	}

	public List<OpeningAgent> findAll() throws Exception {
		openConnection();
		try {
			openingagentDAO = RemittanceDAOFactory.getOpeningAgentDAO(dbManager
					.getConnection());
			return openingagentDAO.findAll();
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}
	}

	public OpeningAgentDataList findOpeningAgents(OpeningAgent cri)
			throws Exception {
		openConnection();
		try {
			openingagentDAO = RemittanceDAOFactory.getOpeningAgentDAO(dbManager
					.getConnection());
			return openingagentDAO.findOpeningAgents(cri);
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}
	}
	
	//Report
	public JasperPrint prepareOpeningAgentReport(OpeningAgentRpt info) throws Exception {
		openConnection();
		JasperPrint l_jsPrint = null;
		try {
			openingagentDAO = RemittanceDAOFactory.getOpeningAgentDAO(getConnection());

			JRResultSetDataSource l_jrRS = new JRResultSetDataSource(openingagentDAO.prepareOpeningAgentReport(info));

			JasperReport l_jsRpt = (JasperReport) JRLoader
					.loadObjectFromFile(CommonSingleton.ABSOLUTE_PATH
							+ "reports/OpeningAgent.jasper");
			HashMap<String, Object> l_params = new HashMap<String, Object>();
			l_params.put("company", "MBC");
			l_jsPrint = JasperFillManager.fillReport(l_jsRpt, l_params, l_jrRS);

		} catch (JRException je) {
			throw je;
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}

		return l_jsPrint;

	}
}
